import Vue from 'vue'
import axios from 'axios'
import { baseURL, contentType, debounce, failureCode, invalidCode, noPermissionCode, requestTimeout, successCode, tokenName } from '@/config'
import store from '@/store'
import qs from 'qs'
import router from '@/router'

let loadingInstance

/**
 * @description 处理code异常
 * @param {*} code
 * @param {*} msg
 */
const handleCode = (code, msg) => {
  switch (code) {
    case failureCode:
      Vue.prototype.$baseNotify(msg, `请求错误`, 'error')
      break
    case invalidCode:
      Vue.prototype.$baseNotify(msg, `认证错误`, 'error')
      router.push({ path: '/login' }).catch(() => {})
      break
    case noPermissionCode:
      Vue.prototype.$baseNotify(msg, `认证授权错误`, 'error')
      store.dispatch('user/resetAccessToken').catch(() => {})
      window.setTimeout(() => {
        location.reload()
      }, 2000)
      break
    default:
      Vue.prototype.$baseNotify(msg, `系统错误`, 'error')
      break
  }
}

const instance = axios.create({
  baseURL,
  timeout: requestTimeout,
  headers: {
    'Content-Type': contentType,
  },
})

instance.interceptors.request.use(
  (config) => {
    if (store.getters['user/accessToken']) {
      config.headers[tokenName] = store.getters['user/accessToken']
    }
    //这里会过滤所有为空、0、false的key，如果不需要请自行注释
    if (config.data) {
      config.data = Vue.prototype.$baseLodash.pickBy(config.data, Vue.prototype.$baseLodash.identity)
    }
    if (config.data && config.headers['Content-Type'] === 'application/x-www-form-urlencoded;charset=UTF-8') {
      config.data = qs.stringify(config.data)
    }
    if (debounce.some((item) => config.method.includes(item))) {
      loadingInstance = Vue.prototype.$baseLoading()
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

instance.interceptors.response.use(
  (response) => {
    if (loadingInstance) {
      loadingInstance.close()
    }
    const { code, msg } = response.data

    // 是否操作正常
    if (successCode.includes(code)) {
      return response.data
    } else {
      handleCode(code, msg)
      return Promise.reject(
        '请求异常拦截:' +
          JSON.stringify({
            url: response.config.url,
            code,
            msg,
          }) || 'Error'
      )
    }
  },
  (error) => {
    if (loadingInstance) {
      loadingInstance.close()
    }
    const { response, message } = error
    if (error.response && error.response.data) {
      const { status, data } = response
      handleCode(status, data.msg || message)
      return Promise.reject(error)
    } else {
      let { message } = error
      if (message === 'Network Error') {
        message = '连接异常'
      }
      if (message.includes('timeout')) {
        message = '请求超时'
      }
      if (message.includes('Request failed with status code')) {
        const code = message.substr(message.length - 3)
        message = '请求异常' + code
      }
      Vue.prototype.$baseMessage(message || `请求未知异常`, 'error')
      return Promise.reject(error)
    }
  }
)

export default instance
